<?php
namespace app\index\controller;
use app\common\controller\ArticalCm;
use app\common\controller\CommonFun;
use app\common\controller\LogsCm;
use app\common\controller\UserCm;
use app\index\model\Pass;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;
use think\Validate;
use think\Session;
use app\index\model\Comment;
use app\index\model\Lists;

/**
 * @property string content
 */
class Index extends BaseController
{
    /**
     * 初始化数据
     * @return mixed
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function index(){
		return $this->fetch();
    }

    /**
     * 检验是否在线
     * @param Request $request
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function checkOnline(Request $request)
    {
        $return['status'] = 0;
        $username = $request->param('user');
        $sid = $request->param('sid');
        $obj_manager = new UserCm();

        if(!empty($username))
        {
            $sid_db = $obj_manager->GetField($username, 'sid');

            $name=Session::get('name');
            if ($sid != $sid_db || !isset($sid) || empty($name)){

				Session::clear();
                $return['status'] = 1;
            }
        }
        return $return;

    }

    /**获取文章数据
     * @return mixed
     * @throws DbException
     * @author LeeBW
     * @date 2020-12-17 20:47
     */
    public function getArticalInfo()
    {

        $title=$this->request->param('title', '');
        $startDate=$this->request->param('startDate', '');
        $endDate=$this->request->param('endDate', '');
        $start = $this->request->param('start', '');
        $limit = $this->request->param('limit', '');
        $module = $this->request->param('module', '');

        //用户名查找
        $username = $this->request->param('username', '');
        $private = $this->request->param('private', '');
        $label  = $this->request->param('label', '');
        //审核
        $pass  = $this->request->param('pass', '');

        if ($start == '')
            $start = 0;

        if (empty($limit)) {

            $limit = 50;
        }
        $cdn =[];
        $cdn['private'] = 0; //私密
        $cdn['pass_auth'] = 0; //审核通过

        if($label ==1103)
        {
            $cdn['private'] = ['in',[0,1]]; //私密
            $cdn['pass_auth'] = ['in',[0,1]]; //审核
        }
        if($title!='')
        {
            $cdn['title'] =['LIKE',"%$title%"];
        }
        if($pass!='')
        {
            $cdn['pass_auth'] = $pass;
        }
        if($module!='')
        {
            $cdn['module'] = $module;
        }
        //用户名
        if($username !='')
        {
            $cdn['username'] = $username;
        }
        //私密
        if($private !='')
        {
            $cdn['private'] = $private;
        }
        if($startDate!='' && $endDate!= '')
        {
            $cdn['create_time'] = ['between',[$startDate.' 00:00:00',$endDate.' 23:59:59']];

        }
//		$lists=Lists::where($cdn)->order('create_time desc')->paginate();
//        foreach ($lists as $a) {
//            $a['count']=count($a->comments);
//        }
//        $list = $lists->toArray();

        $article_ob = new ArticalCm();

        $lists = $article_ob->getArticleData($start,$limit,$cdn,'create_time desc');
        //总数据
        $all_data  = $article_ob->getArticleCount($cdn);

        //管理员等级
        $field = 'level';

        $level = Db::name('user')->field($field)->where('username',$this->username)->value('level');

        $comment_ob = new Comment();
        if(!$lists)
        {
            $data['status'] = 1;
            $data['msg'] = '暂无数据！';
            return $data;
        }

        $user_obj = new UserCm();
        foreach ($lists as &$value) {
            $comments = $comment_ob->where('article_id',$value['id'])->count();

            $cdn['id'] = $value['id'];

            $personal_article = $article_ob->GetField($cdn,'username');
            $user_level = $user_obj->GetField($this->username,'level');

            if(($personal_article===$this->username) || $user_level===0)
                {
                    $value['change_auth']=true;
                }
            else{
                    $value['change_auth']=false;
                }
            $value['count']=$comments;
            if($value['module'] == 0)
            {
                $value['module'] = '其他';
            }
            elseif($value['module'] == 1)
            {
                $value['module'] = '吉他';
            }
            else{
                $value['module'] = '钢琴';
            }
        }
        // 总页数
        $lock_total_page = ceil($all_data / $limit);
        if ($lock_total_page < 1) {
            $lock_total_page = 1;
        }

		if(!empty($lists))
        {
            foreach ($lists as &$va)
            {
                unset($va['comments']);
                unset($va['content']);

            }
        }


        $return['status'] = 0;
        $return['msg'] = '查询成功';
        $return['level']  =true;
        if(isset($level) && $level == 0)
        {
            $return['level'] = false;
            $return['auth_level'] = 0;
        }
        $data['list'] = !empty($lists) ? $lists:[];
        $data['page']['total_page'] = !empty($lock_total_page) ? $lock_total_page:0;
        $data['page']['total_num'] = $all_data;
        $return['data'] = $data;
        return $return;
    }


//    /**注销。清除session
//     * @author LeeBW
//     * @date 2020-12-16 15:50
//     */
//    public function out(){
//		Session::clear();
//		return $this->success('退出成功',$this->path);
//	}



    /**
     *查询留言板
     * @param $id
     * @return mixed
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function getDetailsInfo(){
        $id=$this->request->param('id', '');
		$article=Lists::get($id);
		$article->content = htmlspecialchars_decode($article->content);
        $article = $article->toArray();

//		$comments=$article->comments()->paginate();

        $comments=Db::name('comment')->field('id,username,content,create_time')->where('article_id',$id)->select();

                if(!empty($comments))
                {
                    foreach ($comments as $key=> &$value1)
                    {
                        $value1['content'] = htmlspecialchars_decode($value1['content']);
                    }
                }

//		$this->assign('article',$article);
//		$this->assign('comments',$comments);
//		return $this->fetch();

        $data['status'] = 0;
        $data['msg'] = '查询成功';
        $data['artical_list'] = isset($article) ? $article:[];
        $data['comments_list'] = isset($comments) ? $comments:[];
        return json($data);
	}

    /**
     * 增加一次访问次数
     * @param Request $request
     * @return mixed
     * @throws \think\Exception
     * @author LeeBW
     * @date 2020-12-24 14:19
     */
    public function incrementCount(Request $request)
    {
        $id = $request->param('id');
        $name = $request->param('user');

//        if(empty($name) && ($this->CheckSid($name,$this->sid)))
        if(empty($name))
        {
            $data['status'] = 1;
            $data['msg']  ='请登录！';
            return $data;
        }
        //文章增加一次访问次数
        Db::name('article')->where('id',$id)->setInc('label_times');
        $data['status'] = 0;

        return $data;
    }

    /**
     *查询留言板
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function read(Request $request){

        $id = $request->param('id');
        $name = $request->param('name');
        if(!$this->checkSid($this->username,$this->sid))
        {
            return $this->error('请登录！','/login');
        }
        $article=Lists::get($id);

        $article->content=htmlspecialchars_decode($article->content);
        $comments=$article->comments()->select();

        $level = Db::name('user')->where('username',$name)->value('level');
        $article_user = Db::name('article')->where('id',$id)->value('username');
        $level_mes = Db::name('user')->where('username',$article_user)->value('level_mes');

        $this->assign('article',$article);
        $this->assign('comments',$comments);
        $this->assign('level',$level);
        $this->assign('level_mes',isset($level_mes) ? $level_mes:0);

        return $this->fetch();
    }
    /**
     *回复留言板
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \think\Exception
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function reply(Request $request){

        $id = $request->param('id');
        $name = $request->param('name');
        if(!$this->checkSid($this->username,$this->sid))
        {
            return $this->error('请登录！','/login');
        }
        $article=Lists::get($id);

        $article->content=htmlspecialchars_decode($article->content);
        $comments=$article->comments()->select();

        $level = Db::name('user')->where('username',$name)->value('level');
        $article_user = Db::name('article')->where('id',$id)->value('username');
        $level_mes = Db::name('user')->where('username',$article_user)->value('level_mes');

        $this->assign('article',$article);
        $this->assign('comments',$comments);
        $this->assign('level',$level);
        $this->assign('level_mes',$level_mes ? $level_mes:0);

        return $this->fetch();
    }



    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author LeeBW
     * @date 2020-12-23 18:22
     */
    public function readData(Request $request)
    {
        $id = $request->param('id');
        $name = $request->param('user');

        $list = new Lists();

        $article = $list->where('id',$id)->find();
        if(empty($article))
        {
            $data['status'] = 1;
            $data['msg'] = '查询失败';
            return json($data);
        }
        $article['content']=htmlspecialchars_decode($article['content']);
        $comments = Db::name('comment')->where('article_id',$id)->select();
        $data['status'] = 0;
        $data['msg'] = '查询成功';
        $data['list'] = isset($article)?$article:[];
        $data['data'] = isset($comments)?$comments:[];
        return json($data);
    }


    /**
     * @param Request $request
     * @return mixed
     * @throws DbException
     */
    public function change(Request $request){
        $id = $request->param('id');
//        $this->check();
        $article=Lists::get($id);
        $article->content=htmlspecialchars_decode($article->content);
        $this->assign('article',$article);
        return $this->fetch();
    }

    /**
     * 引导修改
     * @param Request $request
     * @return \think\response\Json
     * @author LeeBW
     * @date 2020-12-24 17:18
     */
    public function change_html(Request $request){

        if(!($this->CheckSid($this->username,$this->sid)))
        {
            $data['status'] = 0;
            $data['msg'] = '查询成功';
            return json($data);
        }

        $data['status'] = 1;
        $data['msg'] = '请登录！';
        return json($data);
    }

    /**
     * 添加评论
     * @param $id
     * @param $name
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function addcomment($id,$name){
        $comment = new Comment;
        $article = new Lists();
        $username = $name;
        $content = $_POST['content'];
		$comment->article_id=$id;
		if($username!= '')
        {
            $comment->username=$username;
        }
		if($content!= '')
        {
            $comment->content=$content;
        }

		$comment->create_time=date('Y-m-d H:i:s');
        $comment->req_ip = $this->get_ip();
        if($username=='' ||$content=='')
        {
            $this->error('请输入标题和内容！');
        }
		if($comment->save()){
            $article->save(['new_com'=>0],['id'=>$id]);
            LogsCm::WriteAdmLog($username,'添加评论成功：'.$content);
			$this->success('添加评论成功！','index/read'.'?id='.$id);
		}else{
			$this->error('添加评论失败！');
		}
	}

    /**
     * 删除评论
     * @throws \think\Exception
     * @throws DbException
     * @throws \think\exception\PDOException
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function delete(){

	if(($this->username) =='')
	{
		    $data['status'] = 1;
            $data['msg'] = '请登录！';

            return $data;
	}
//		$this->check();
		
        $id=$this->request->param('id', '');

		$article=Lists::get($id);


//        if($article){
//            $article->delete();
//            $article->comments()->delete();
//            $this->success('删除记录成功！',$this->path);
//        }else{
//            $this-error('没有要删除的记录！');
//        }

        if($article){
            $array = json_encode($article->toArray(),true);
			$article->delete();
			$article->comments()->delete();

            $data['status'] = 0;
            $data['msg'] = '删除成功！';
            LogsCm::WriteAdmLog($this->username,'删除评论：'.$array);

            return $data;
		}else{
            $data['status'] = 1;
            $data['msg'] = '没有删除的记录！';

            return $data;
		}
	}

    /**
     * 添加留言渲染模板，可检测是否登录
     * @return mixed
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function add(){
//		$this->check();
		return $this->fetch();
	}

    /**添加文章
     * @param $name
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @author LeeBW
     * @date 2020-12-16 15:50
     */
    public function add_article($name){

		$article=new Lists;
		$data['title']=$_POST['title'];
		$data['module']=$_POST['module'];
        $data['private'] =isset($_POST['private']) ? $_POST['private']:1;
		$data['content']=htmlspecialchars($_POST['content']);

		$data['create_time']=date('Y-m-d H:i:s');
        if($data['private'] = 1)
        {
            $data['pass_auth'] = 0;
        }
        $visitor = date('Y') . CommonFun::GetRandomString(14,1);
		if((!empty($name)))
        {
            $data['username']=$name;
            //增加经验
            $level = 0;
            $exp  = Db::name('user')->where('username',$name)->value('exp');
            $exp +=10;
            $remainder = intval(floor($exp/100));
            if($remainder == 0)
            {
                $level = 1;
            }
            else{
                $level = $remainder;
            }
            //升级
            Db::name('user')->where('username',$name)->update(['level_mes'=>$level]);
            Db::name('user')->where('username',$name)->update(['exp'=>$exp]);
            if($name==='unknown')
            {
                $data['username']='游客'.$visitor;
            }
        }
		$data['req_ip']=$this->get_ip();
		$rule1=[
			'title'=>'require',
			'content'=>'require'
		];

		$rule2=[
			'module'=>'require',
		];
		$validate1 = new Validate($rule1);
		$validate2 = new Validate($rule2);
		if(!$validate1->check($data)){
			$this->error('请输入标题和内容！');
		}
		if(!$validate2->check($data)){
			$this->error('请选择模块！');
		}
		if($article->save($data)){
			$this->success('留言发布成功！','/');
		}else{
			$this->error('留言发布失败！');
		}
	}

    /**
     * 修改文章
     * @param Request $request
     */
    public function change_article(Request $request){
		$article=new Lists;
		$data['title']=$_POST['title'];


		$data['content']=htmlspecialchars($_POST['content']);

		$data['update_time']=date('Y-m-d H:i:s');

		$id  = $request->param('id');
//		$name  = $request->param('user');

//		if((!empty($name)))
//        {
//            $data['username']=$name;
//
//        }
		$data['req_ip']=$this->get_ip();
		$rule=[
			'title'=>'require',
			'content'=>'require'
		];
		$validate=new Validate($rule);

		if(!$validate->check($data)){
			$this->error('请输入标题和内容！');
		}
		if($article->save($data,['id'=>$id])){
//            LogsCm::WriteAdmLog($name,'修改文章：'.json_encode($data,true));
			$this->success('留言修改成功！','index/change'.'?id='.$id);
		}else{
			$this->error('留言修改失败！');
		}
	}


    /**
     * 查询个人信息
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function personal_info()
	{
	    $username = $this->username;
        $user = new  Pass();
        $article  = new  Lists();

        $field = 'nick_name,condition,level_mes';
        $list = $user->field($field)->where('username',$username)->find();
        //文章数
        $count = $article->where('username',$username)->count();

        $data = ['nick_name'=>$list['nick_name'],'condition'=>$list['condition'],'count'=>$count,'level'=>$list['level_mes']];
        $return['status'] = 0;
        $return['msg'] = '查询成功！';
        $return['data'] = $data;
        return $return;
	}

    /**
     * 查询用户的等级
     * @return mixed
     */
    public function checkUserInfo()
    {

        //管理员等级
        $field = 'level';

        $level = Db::name('user')->field($field)->where('username',$this->username)->value('level');

        $return['status'] = 0;
        $return['msg'] = '查询成功';
        $return['auth_level'] = 1;
        if(isset($level) && $level == 0)
        {
            $return['auth_level'] = 0;
        }
        return $return;
    }

}
